<template>
  <div class="columns-editor">
    <div class="section-header">
      <h4>表格列配置</h4>
    </div>
    
    <div class="columns-list">
      <div v-for="(column, index) in columns" :key="index" class="column-item">
        <el-collapse>
          <el-collapse-item :title="`列 ${index + 1}: ${column.label || '未命名列'}`">
            <el-form label-position="left" label-width="80px" size="small">
              <el-form-item label="列标题">
                <el-input 
                  v-model="column.label" 
                  placeholder="列标题" 
                  @change="updateColumns"
                />
              </el-form-item>
              
              <el-form-item label="字段属性">
                <el-input 
                  v-model="column.prop" 
                  placeholder="对应数据字段名" 
                  @change="updateColumns"
                />
              </el-form-item>
              
              <el-form-item label="列宽">
                <div class="input-with-unit">
                  <el-input-number 
                    v-model="column.width" 
                    :min="50"
                    :step="10"
                    controls-position="right"
                    placeholder="列宽(px)" 
                    @change="updateColumns"
                  />
                  <span class="unit-label">px</span>
                </div>
              </el-form-item>
              
              <el-form-item label="对齐方式">
                <el-select 
                  v-model="column.align" 
                  placeholder="对齐方式"
                  @change="updateColumns"
                >
                  <el-option label="左对齐" value="left" />
                  <el-option label="居中" value="center" />
                  <el-option label="右对齐" value="right" />
                </el-select>
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeColumn(index)"
                >
                  删除此列
                </el-button>
              </el-form-item>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </div>
      
      <div v-if="columns.length === 0" class="no-columns">
        <p>当前没有列。点击添加按钮创建列。</p>
      </div>
    </div>
    
    <div class="columns-actions">
      <el-button 
        type="primary" 
        size="small" 
        @click="addColumn"
      >
        添加列
      </el-button>
    </div>

    <div class="section-header">
      <h4>表格数据示例</h4>
    </div>
    <div class="table-data-editor">
      <el-input
        type="textarea"
        v-model="tableDataJson"
        :rows="5"
        placeholder="以JSON格式输入表格数据示例"
        @change="updateTableData"
      />
      <p class="hint">请输入有效的JSON数组格式，如：[{"id":1,"name":"测试1"},{"id":2,"name":"测试2"}]</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useDesignStore } from '@/stores/designStore';

const props = defineProps<{
  componentId: string;
}>();

const designStore = useDesignStore();

// 列数据结构
interface TableColumn {
  label: string;
  prop: string;
  width?: number;
  align?: 'left' | 'center' | 'right';
  fixed?: boolean | 'left' | 'right';
  sortable?: boolean;
}

const columns = ref<TableColumn[]>([]);
const tableDataJson = ref('');

// 初始化列数据
onMounted(() => {
  loadColumnsAndData();
});

// 当组件ID变化时重新加载列
watch(() => props.componentId, () => {
  loadColumnsAndData();
});

// 从store中加载列
const loadColumnsAndData = () => {
  const component = designStore.findComponentById(designStore.canvasComponents, props.componentId);
  if (!component) return;

  // 加载列配置
  const existingColumns = component.props?.columns || [];
  columns.value = [...existingColumns];
  
  // 确保至少有一个列
  if (columns.value.length === 0) {
    columns.value = [
      { label: 'ID', prop: 'id', width: 100, align: 'center' },
      { label: '名称', prop: 'name', width: 200, align: 'left' }
    ];
    updateColumns();
  }

  // 加载表格数据
  try {
    const existingData = component.props?.data || [];
    tableDataJson.value = JSON.stringify(existingData, null, 2);
  } catch (e) {
    console.error('加载表格数据失败:', e);
    tableDataJson.value = '[{"id":1,"name":"测试1"},{"id":2,"name":"测试2"}]';
    updateTableData();
  }
};

// 添加新列
const addColumn = () => {
  const newColumnNumber = columns.value.length + 1;
  columns.value.push({
    label: `列${newColumnNumber}`,
    prop: `column${newColumnNumber}`,
    width: 150,
    align: 'center'
  });
  updateColumns();
};

// 移除列
const removeColumn = (index: number) => {
  columns.value.splice(index, 1);
  updateColumns();
};

// 更新store中的列
const updateColumns = () => {
  designStore.updateComponentProps(props.componentId, {
    columns: columns.value
  });
};

// 更新表格数据
const updateTableData = () => {
  try {
    const parsedData = JSON.parse(tableDataJson.value);
    if (Array.isArray(parsedData)) {
      designStore.updateComponentProps(props.componentId, {
        data: parsedData
      });
    } else {
      console.error('表格数据格式不正确，应为数组');
    }
  } catch (e) {
    console.error('解析表格数据失败:', e);
  }
};
</script>

<style scoped>
.columns-editor {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h4 {
  margin: 0;
  font-size: 14px;
  color: #303133;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.columns-list {
  margin-bottom: 15px;
}

.column-item {
  margin-bottom: 15px;
}

.no-columns {
  padding: 10px;
  color: #909399;
  font-size: 14px;
  text-align: center;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  margin-bottom: 10px;
}

.columns-actions {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.unit-label {
  margin-left: 5px;
  color: #909399;
  font-size: 12px;
}

.table-data-editor {
  margin-bottom: 20px;
}

.hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

:deep(.el-collapse-item__header) {
  font-size: 13px;
  color: #409EFF;
  font-weight: 500;
}

:deep(.el-form-item__label) {
  font-size: 13px;
  color: #606266;
}

:deep(.el-input-number), 
:deep(.el-select),
:deep(.el-input) {
  width: 100%;
}

.input-with-unit {
  display: flex;
  align-items: center;
  width: 100%;
}

.input-with-unit :deep(.el-input-number) {
  flex: 1;
}
</style> 